package it.polimi.registration.business.weather;

import it.polimi.registration.business.security.entity.Event;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.json.JSONArray;
import org.json.JSONObject;

public class PropositionFactory {
	
	private static final String URL = "http://api.openweathermap.org/data/2.5/forecast/daily?units=metric&cnt=16&q=";

	private String url;
	private Event e;

	public PropositionFactory(Event e) throws Exception {
		this.e = e;
		this.url = URL + e.getLocation();
	}

	public long getNextSunnyDay() throws Exception {
		String result = readJsonFromURL(this.url);
		JSONObject jsonObject = new JSONObject(result);
		
		Calendar now = new GregorianCalendar();
		
		JSONArray list = jsonObject.getJSONArray("list");
		JSONObject temp;
		JSONArray weather;
		int weather_id = 0;
		long dt = 0;
		
		int i = 0;
		for(i=0; i<list.length(); i++) {
			temp = list.getJSONObject(i);
			if(temp.has("dt")) {
				weather = temp.getJSONArray("weather");
				weather_id = weather.getJSONObject(0).getInt("id");
				if(weather_id == 800 || weather_id == 801 || weather_id == 802) {
					dt = temp.getLong("dt");
					return dt;
				}
			}				
		}
		
		return dt;
	}
	
	private String readJsonFromURL(String urlString) throws Exception {
	    BufferedReader reader = null;
	    try {
	        URL url = new URL(urlString);
	        reader = new BufferedReader(new InputStreamReader(url.openStream()));
	        StringBuffer buffer = new StringBuffer();
	        int read;
	        char[] chars = new char[1024];
	        while ((read = reader.read(chars)) != -1)
	            buffer.append(chars, 0, read); 

	        return buffer.toString();
	    } finally {
	        if (reader != null)
	            reader.close();
	    }
	}
}
